<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Article;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $type = (int)request()->get('type');
        $categoryId = (int)request()->get('category_id');
        $items = Article::when($type, function ($query) use ($type) {
            $query->where(compact('type'));
        })
            ->when($categoryId, function ($query) use ($categoryId) {
                $query->where('category_id', $categoryId);
            })
            ->latest('orderby')
            ->paginate(request()->input('per_page', 10));
        return $this->successful($items);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data  = $request->all();
        $data['desc'] = mb_substr(strip_tags($data['content']), 0, 100);
        return $this->successful(Article::create($data));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Article  $article
     * @return \Illuminate\Http\Response
     */
    public function show(Article $article)
    {
        return $this->successful($article);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  \App\Models\Article  $article
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Article $article)
    {
        $data = $request->all();
        $html = html_entity_decode($data['content']);
        $data['content'] = $html;

        $desc = str_replace([PHP_EOL, " "], ['<br/>', ''], strip_tags($html));
        $data['desc'] = mb_substr($desc, 0, 100);
        $article->update($data);
        return $this->successful();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Article  $article
     * @return \Illuminate\Http\Response
     */
    public function destroy(Article $article)
    {
        $article->delete();
        return $this->successful();
    }

    public function batchDelete()
    {
        $ids = request()->post('id');
        if (is_array($ids)) {
            foreach ($ids as $id) {
                $this->destroy(Article::find($id));
            }
            return $this->successful();
        }
    }
}
